<template>
  <el-upload
    v-loading="loading"
    class="uploader-one"
    action="#"
    :show-file-list="false"
    :on-success="handlSuccess"
    :before-upload="beforeUpload"
    :on-error="handleError"
    :http-request="httpRequest"
  >
    <img v-if="imageUrl" title="点击可以更换图片" :src="imageUrl" class="avatar">
    <i v-else class="el-icon-plus uploader-icon" />
  </el-upload>
</template>

<script>
// 图片上传/下载
import { fileUploadCert, fileUpload, imgDownLoad, fileUploadFirst } from '@/api/common/upload.js'

export default {
  name: 'ImgUploadOne',
  props: {
    // 上传的附件回显
    editFileList: {
      type: Array,
      default: function() {
        return []
      }
    },
    certId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      loading: false,
      // 回显图片
      imageUrl: ''
    }
  },
  watch: {
    editFileList: {
      deep: true,
      immediate: true,
      handler(val, oldVal) {
        console.log(val)
        if (val && val.length > 0) {
          this.imgDownLoad(val)
        } else {
          this.imageUrl = ''
        }
      }
    }
  },
  methods: {
    httpRequest(e) {
      this.loading = true
      const file = new FormData()
      file.append('file', e.file)
      fileUploadCert(file, this.certId).then((res) => {
        if (res.data) {
          this.$emit('getCertData', res.data, this.certId)
        }
        fileUpload(file).then((response) => {
          e.onSuccess(response)
          this.loading = false
        })
          .catch((err) => {
            e.onError(err)
          })
      })
    },
    // 上传成功的回调
    handlSuccess(res, file) {
      if (res) {
        this.imageUrl = URL.createObjectURL(file.raw)
        const { fileId, fileName, uploadDate } = res.data
        const fileList = {
          fileName,
          fileId,
          createTime: uploadDate
        }// 图片数据
        console.log(res.data)
        this.$emit('getFilePic', [fileList])
        this.msgSuccess('上传成功')
      } else {
        this.msgError(res.message)
      }
    },
    // 上传失败的回调
    handleError(err, file, fileList) {
      if (err.message === 'Network Error') {
        this.msgError('上传文件过大或者磁盘已满')
      } else {
        this.msgError('上传文件过大或者磁盘已满')
      }
    },
    // 上传前的回调
    beforeUpload(file) {
      const isLt30M = file.size / 1024 / 1024 < 30
      if (!isLt30M) {
        this.msgError('上传文件大小不能超过 30MB!')
        return false
      }
      return true
    },
    // 图片回显
    imgDownLoad(id) {
      console.log(this.certId)
      if (this.certId) {
        imgDownLoad({ id: id[0].fileId }).then(res => {
        // 将从后台获取的图片流进行转换
          this.imageUrl = 'data:image/png;base64,' + btoa(new Uint8Array(res).reduce((data, byte) => data + String.fromCharCode(byte), ''))
        })
      } else {
        fileUploadFirst({ id: id[0].fileId }).then((res) => {
          this.imageUrl = 'data:image/png;base64,' + btoa(new Uint8Array(res).reduce((data, byte) => data + String.fromCharCode(byte), ''))
        })
      }
    }
  }
}
</script>

<style lang='scss' scoped>
.uploader-one {
  width: 100px;
  height: 100px;
  border-radius: 6px;
  border: 1px dashed #d9d9d9;
  overflow: hidden;
}
.uploader-one .el-upload {
  border: 1px dashed #d9d9d9;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.uploader-one .el-upload:hover {
  border-color: #409eff;
}
.uploader-icon {
  font-size: 22px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  border-radius: 6px;
  display: block;
}
</style>
